package com.xuexi.controller;

import com.easygo.utils.MessageResults;
import com.xuexi.api.AdminClient;
import com.xuexi.api.LoginLogClient;
import com.xuexi.easygo.pojo.Admin;
import com.xuexi.easygo.pojo.LoginLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@Scope("prototype")
public class AdminController {

    @Autowired
    AdminClient adminClient;

    @Autowired
    LoginLogClient loginLogClient;

    @RequestMapping("admin_login")
    @ResponseBody
    public MessageResults adminLogin(Admin admin,String ip,String city, HttpSession session){

        System.out.println("IP="+ip);
        System.out.println("city="+city);
        //获取到用户登录的真是IP和城市地址，这样才能新增到数据库，多种做法
        //1、获取到IP之后，调用WebService，查询IP对应的城市（功能更强大一些）
        //2、直接JS前端调用接口（目前这个位置正好使用）
        MessageResults results =null;
        Admin admin1 = adminClient.adminLogin(admin);
        System.out.println("当前登录的用户是="+admin1);
        if(admin1!=null){
            //如果是1，表示没有被封禁
            if("1".equals(admin1.getStatus())){
                System.out.println("登录成功");
                //登录的日志
                LoginLog loginLog = new LoginLog(ip,admin1.getUsername(),city);
                loginLog.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                System.out.println("要新增的日志对象:"+loginLog);
                int count = loginLogClient.addLoginLog(loginLog);

                //将用户的session传过去
                session.setAttribute("adminLogin",admin1);
                results = new MessageResults(200,"登录成功");
            }else{
               results = new MessageResults(303,"该用户已被冻结，请联系管理员") ;
            }
        }else {
            System.out.println("失败");
            results = new MessageResults(500,"登录失败");

        }
        return results;
    }

    @RequestMapping("admin_logout")
    public String adminLogout(HttpSession session){
        session.invalidate();
        return "login";
    }

    //异步获得登录日志
    @ResponseBody
    @RequestMapping("admin_getLoginLogs")
    public List<LoginLog> getLoginLogs(HttpSession session){
        Admin admin = (Admin)session.getAttribute("adminLogin");
        List<LoginLog> myLoginLogs = loginLogClient.getMyLoginLogs(admin.getUsername());
        return myLoginLogs;
    }

}
